package com.king.player.kingplayer;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import androidx.core.content.ContextCompat;

/**
 * Description：
 * Created on 2024/11/7 15:10
 * Organization:华云
 * author：AHuangSHang
 **/
public class ProgressView extends View {

    private Paint linePaint;
    private static final int LINE_COUNT = 12; // 菊花的线条数量
    private static final float LINE_LENGTH = 40f; // 线条长度
    private static final int ROTATION_SPEED = 5; // 每帧旋转的角度
    private int currentRotation = 0; // 当前旋转角度
    private int progress = 0; // 当前进度（用于控制颜色）

    public ProgressView(Context context) {
        super(context);
        init();
    }

    public ProgressView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ProgressView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        // 初始化画笔
        linePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        linePaint.setStyle(Paint.Style.STROKE);
        linePaint.setColor(Color.LTGRAY); // 初始颜色
        linePaint.setStrokeCap(Paint.Cap.ROUND);
        linePaint.setStrokeWidth(8f);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // 根据进度设置颜色
        setProgressColor();

        // 计算旋转中心
        float centerX = getWidth() / 2f;
        float centerY = getHeight() / 2f;

        // 逐个绘制菊花的线条
        for (int i = 0; i < LINE_COUNT; i++) {
            canvas.save();
            canvas.rotate(360f / LINE_COUNT * i + currentRotation, centerX, centerY);
            canvas.drawLine(
                    centerX,
                    centerY - LINE_LENGTH, // 绘制的开始位置
                    centerX,
                    centerY - LINE_LENGTH * 2, // 绘制的结束位置
                    linePaint
            );
            canvas.restore();
        }

        // 增加旋转角度，使菊花效果旋转
        currentRotation += ROTATION_SPEED;
        if (currentRotation >= 360) currentRotation = 0;

        // 触发重绘
        postInvalidateDelayed(16);
    }

    // 根据进度设置颜色
    private void setProgressColor() {
        int color;
        if (progress <= 30) {
            color = ContextCompat.getColor(getContext(), android.R.color.holo_red_light);
        } else if (progress <= 70) {
            color = ContextCompat.getColor(getContext(), android.R.color.holo_orange_light);
        } else {
            color = ContextCompat.getColor(getContext(), android.R.color.holo_green_light);
        }
        linePaint.setColor(color);
    }

    // 设置进度的方法
    public void setProgress(int progress) {
        this.progress = Math.max(0, Math.min(progress, 100)); // 限制进度范围为0-100
        invalidate();
    }


}

